<template>
  <div>
    <!-- 日历组件 -->
    <a-calendar v-model:value="selectedDate" @select="handleDateSelect" :locale="locale">
      <!-- 自定义日历单元格内容 -->
      <template #dateCellRender="{ current }">
        <div class="calendar-tasks">
          <div v-for="(task, index) in getTasksForDate(current)" :key="index" class="task-item-small">
            <span @click.stop="handleTaskComplete(task)" class="task-icon-small">
              <component :is="task.isCompleted === '1' ? CheckCircleOutlined : MinusCircleOutlined" :style="{ color: task.isCompleted === '1' ? 'green' : 'gray' }" />
            </span>
            <span :style="{ textDecoration: task.isCompleted === '1' ? 'line-through' : 'none' }">{{ task.taskText }}</span>
<!--            <a-button type="link" @click.stop="removeTask(task.id)">删除</a-button>-->
          </div>
        </div>
      </template>
    </a-calendar>

    <!-- 添加计划的弹窗 -->
    <a-modal v-model:visible="showTaskModal" :title="`${selectedDate.format('YYYY-MM-DD')} 的计划`" width="600px" @ok="saveTasks" okText="确认" cancelText="取消">
      <div v-if="tasks.length === 0" class="no-tasks">暂无任务</div>
      <div v-else>
        <div v-for="(task, index) in tasks" :key="index" class="task-item">
          <span @click="handleTaskComplete(task)" class="task-icon">
            <component :is="task.isCompleted === '1' ? CheckCircleOutlined : MinusCircleOutlined" :style="{ color: task.isCompleted === '1' ? 'green' : 'gray' }" />
          </span>
          <span :style="{ textDecoration: task.isCompleted === '1' ? 'line-through' : 'none' }">{{ task.taskText }}</span>
          <a-button type="link" @click="removeTask(task.id)">删除</a-button>
        </div>
      </div>
      <a-input
        v-model:value="newTask"
        placeholder="输入新计划"
        @pressEnter="addTask"
        class="new-task-input"
      />
      <a-button type="primary" @click="addTask" style="margin-top: 10px">添加计划</a-button>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { CheckCircleOutlined, MinusCircleOutlined } from '@ant-design/icons-vue';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn'; // 引入中文语言包
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN'; // 引入 Ant Design 中文语言包
import {
  addTaskUsingPost,
  deleteTaskUsingPost,
  listTaskByUserIdUsingPost,
  updateTaskUsingPost
} from "@/api/taskController.js";
import { message } from "ant-design-vue";

dayjs.locale('zh-cn'); // 设置 dayjs 为中文

const selectedDate = ref(dayjs()); // 当前选中的日期
const showTaskModal = ref(false); // 控制任务弹窗显示
const tasks = ref([]); // 当前日期的任务列表
const newTask = ref(''); // 新任务输入框的值
const allTasks = ref([]); // 所有任务列表
const hasDeleteApi = ref(true); // 标记是否有删除接口

// 处理日期选择
const handleDateSelect = async (date) => {
  selectedDate.value = date;
  await loadTasks(); // 加载任务
  showTaskModal.value = true; // 显示任务弹窗
};

// 加载所有任务
const loadAllTasks = async () => {
  try {
    const response = await listTaskByUserIdUsingPost();
    allTasks.value = response.data.data;
    await loadTasks();
  } catch (error) {
    console.error('加载所有任务失败:', error);
  }
};

// 加载任务
const loadTasks = async () => {
  const formattedDate = selectedDate.value.format('YYYY-MM-DD');
  tasks.value = allTasks.value.filter(task => {
    return dayjs(task.taskDate).format('YYYY-MM-DD') === formattedDate;
  });
};

onMounted(async () => {
  await loadAllTasks(); // 初始化时加载所有任务
});

// 保存任务
const saveTasks = () => {
  showTaskModal.value = false;
};

// 添加新任务
const addTask = async () => {
  if (newTask.value.trim()) {
    const taskDate = selectedDate.value.format('YYYY-MM-DD');
    const data = {
      taskDate,
      taskText: newTask.value.trim()
    };
    try {
      await addTaskUsingPost(data);
      await loadAllTasks(); // 添加成功后重新加载所有任务
      newTask.value = '';
    } catch (error) {
      console.error('添加任务失败:', error);
    }
  }
};

// 删除任务
const removeTask = async (id: string) => {
  if (hasDeleteApi.value) {
    try {
      const res = await deleteTaskUsingPost({ id });
      if (res.data && res.data.code === 0) {
        message.success('删除成功');
        await loadAllTasks(); // 删除成功后重新加载所有任务
      } else {
        message.error(`删除失败: ${res.data?.message || '未知错误'}`);
      }
    } catch (error) {
      console.error('删除任务失败:', error);
      message.error('发生错误，请重试');
    }
  }
};

// 处理任务完成状态
const handleTaskComplete = async (task) => {
  const newStatus = task.isCompleted === '1' ? '0' : '1';
  const data = {
    id: task.id,
    isCompleted: newStatus,
    taskDate: dayjs(task.taskDate).format('YYYY-MM-DD'),
    taskText: task.taskText
  };
  try {
    await updateTaskUsingPost(data);
    await loadAllTasks(); // 更新成功后重新加载所有任务
  } catch (error) {
    console.error('更新任务状态失败:', error);
  }
};

// 获取某一天的任务
const getTasksForDate = (date) => {
  const formattedDate = date.format('YYYY-MM-DD');
  return allTasks.value.filter(task => {
    return dayjs(task.taskDate).format('YYYY-MM-DD') === formattedDate;
  });
};
</script>

<style scoped>
.calendar-tasks {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.task-item-small {
  display: flex;
  align-items: center;
  padding: 4px;
  background-color: #f9f9f9;
  border-radius: 4px;
  font-size: 12px;
  transition: background-color 0.3s;
}

.task-item-small:hover {
  background-color: #f0f0f0;
}

.task-icon-small {
  margin-right: 8px;
  cursor: pointer;
}

.task-item-small .ant-btn {
  margin-left: 8px;
  padding: 0;
}

.no-tasks {
  color: #999;
  margin-bottom: 16px;
}

.new-task-input {
  margin-top: 16px;
}
</style>
